package com.caidan.diagram.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/captchar")
public class CaptCharController {
    @GetMapping
    public void createCaptcha(HttpServletResponse response, HttpServletRequest request) throws IOException {
        // 随机4位数字，可重复
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        lineCaptcha.setGenerator(randomGenerator);
        // 重新生成code
        // 2. 获取验证码文本
        String code = lineCaptcha.getCode();
        log.info("验证码：{}", code);
        // 3. 将验证码存入 session
        request.getSession().setAttribute("code", code);
        // 4. 设置响应头
        response.setContentType("image/png");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        // 5. 输出验证码图片到前端
        lineCaptcha.write(response.getOutputStream());
        response.getOutputStream().close();
    }
}
